package pl.edu.pk.adcampaignfacebook.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import pl.edu.pk.adcampaignfacebook.dao.AccountDao;
import pl.edu.pk.adcampaignfacebook.domain.Account;
import pl.edu.pk.adcampaignfacebook.domain.AccountRole;
import pl.edu.pk.adcampaignfacebook.exception.UserExistsException;
import pl.edu.pk.adcampaignfacebook.exception.UserNotFoundException;

@Transactional
@Repository
public class AccountServiceImpl implements AccountService
{
	@Autowired
	AccountDao accountDao;

	@Autowired
	PasswordEncoder passwordEncoder;

//	@Autowired
//	SaltSource saltSource;

	@PersistenceContext
	EntityManager entityManager;

	//@Override
	public void registerAccount(Account account) throws UserExistsException 
	{	
		try
		{
			accountDao.findUsername(account.getUsername());
			throw new UserExistsException();
		}
		catch (UserNotFoundException une)
		{
			entityManager.persist(account);
			account.setPassword(passwordEncoder.encodePassword(account.getPassword(), null));
//			System.out.println(" -----------> PASSWORD1 passenc: " + passwordEncoder.encodePassword(account.getPassword(), saltSource) + " <-------------------------");
//			System.out.println(" -----------> PASSWORD1 passenc: " + passwordEncoder.encodePassword(account.getPassword(), saltSource) + " <-------------------------");
//			System.out.println(" -----------> PASSWORD getpass: " + account.getPassword() + " <-------------------------");
//			System.out.println(" -----------> PASSWORD getpass: " + account.getPassword() + " <-------------------------");
//			account.setPassword("password");
		}
	}
	
	//@Override
	public void registerAccount(Account account, List<AccountRole> ar) throws UserExistsException 
	{	
		try
		{
			accountDao.findUsername(account.getUsername());
			throw new UserExistsException();
		}
		catch (UserNotFoundException une)
		{
			entityManager.persist(account);
//			account.setPassword(passwordEncoder.encodePassword(account.getPassword(), saltSource));
			for (AccountRole arole : ar)
			{
				account.addAccountRole(arole);
			}
		}
	}

//	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException
	{
		try
		{
			return (UserDetails) accountDao.findUsername(username);
		} 
		catch (UserNotFoundException e) 
		{
			throw new UsernameNotFoundException(username);
		}
	}
}
